package com.zhao.newcoder.service.impl;

import com.lambdaworks.crypto.SCryptUtil;
import com.zhao.newcoder.DTO.User;
import com.zhao.newcoder.DTO.response.UserResponse;
import com.zhao.newcoder.Repository.UserRepository;
import com.zhao.newcoder.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * 用户接口实现
 *
 * @author: ZhouBin
 * @date: 2020/10/9 9:17 上午
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class UserServiceImpl implements UserService {

    private final UserRepository userRepository;

    @Override
    public void insertUser(User user) {

    }

    @Override
    public void updateUser(User user) {

    }

    @Override
    public void deleteUser(String id) {

    }

    @Override
    public User findById(String id) {
//        passwordRefresh();
        Optional<User> optionalUser = userRepository.findById(id);
        if (optionalUser.isPresent()){
            return optionalUser.get();
        }else {
            return null;
        }
    }

    /**
     * 使用scrypt加密方式将user密码刷新为wx123456对应密文
     *
     * @author: ZhouBin
     * @date: 2020/10/9 11:36 上午
     * @param
     * @return void
     */
    @Transactional(rollbackFor = Exception.class)
    public void passwordRefresh(){
        List<User> users = userRepository.findAll();
        users.forEach(user -> user.setPassword(SCryptUtil.scrypt("wx123456",32768,8,1)));
        userRepository.saveAll(users);
    }

    @Override
    public List<User> findAll(User user) {
        return userRepository.findAll();
    }

    @Override
    public UserResponse login(UserResponse userResponse) {
        return userResponse;
    }
}